package com.zf.shuashua.advert.mg;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.aliyun.svideo.common.utils.AppInfoUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.download.library.DownloadImpl;
import com.download.library.DownloadListenerAdapter;
import com.download.library.Extra;
import com.download.library.ResourceRequest;
import com.kk.taurus.playerbase.assist.OnVideoViewEventHandler;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.event.OnPlayerEventListener;
import com.kk.taurus.playerbase.player.IPlayer;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;
import com.kk.taurus.playerbase.widget.BaseVideoView;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.vise.xsnow.http.api.ApiService;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.net.BaseObserveListener;
import com.zf.shuashua.net.MyApiService;
import com.zf.shuashua.net.RetrofitUtil;

import java.io.File;
import java.util.HashMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MGRewardActivity extends MGRewardReport implements OnPlayerEventListener {

    /**
     * 是否静音
     */
    private boolean isMute = false;

    /**
     * 视频是否播放完成
     */
    private boolean isPlayComplete = false;

    private FrameLayout playContainer;
    private FrameLayout finishContainer;
    private LinearLayout imgFinishContainer;

    private ImageView ivIconFinish;
    private TextView tvTitleFinish;
    private Button btnActionFinish;

    private Button btnAction;

    private WebView webview;
    private ImageView imgFinish;

    private BaseVideoView mVideoView;
    private TextView tvClose;
    private TextView tvTime;
    private ImageView ivVolume;

    private boolean hasReportClick = false;
    private boolean hasReportStartDown = false;
    private boolean hasReportEndDown = false;
    private boolean hasReportStartInstall = false;

    private CountDownTimer mCountDownTimer = null;
    private long curTime = 0;
    private boolean isPause = false;

    private String packageName = "";


    public static void action(Context context, AdDataBean adDataBean) {
        Intent intent = new Intent(context, MGRewardActivity.class);
        intent.putExtra("AdDataBean", adDataBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mgmob_reward);
        //保持界面常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        initReceiver();

        mAdDataBean = (AdDataBean) getIntent().getSerializableExtra("AdDataBean");

        tvClose = findViewById(R.id.tv_close);
        tvTime = findViewById(R.id.tv_time);
        ivVolume = findViewById(R.id.iv_volume);
        ImageView ivIcon = findViewById(R.id.iv_icon);
        TextView tvTitle = findViewById(R.id.tv_title);
        btnAction = findViewById(R.id.btn_action);

        ivIconFinish = findViewById(R.id.iv_icon_finish);
        tvTitleFinish = findViewById(R.id.tv_title_finish);
        btnActionFinish = findViewById(R.id.btn_action_finish);

        mVideoView = findViewById(R.id.videoView);
        playContainer = findViewById(R.id.play_container);
        finishContainer = findViewById(R.id.finish_container);
        imgFinishContainer = findViewById(R.id.img_finish_container);
        webview = findViewById(R.id.web_container);
        initWebView();
        imgFinish = findViewById(R.id.img_finish);

        ivVolume.setOnClickListener(v -> {
            mVideoView.setVolume(isMute ? 1 : 0, isMute ? 1 : 0);
            isMute = !isMute;
            ivVolume.setImageResource(isMute ? R.drawable.ic_volume_off : R.drawable.ic_volume_on);
        });

        ReceiverGroup receiverGroup = new ReceiverGroup();
        receiverGroup.addReceiver("load_cover", new LoadingCover(MGRewardActivity.this));
        mVideoView.setReceiverGroup(receiverGroup);
        mVideoView.setOnPlayerEventListener(this);
        mVideoView.setEventHandler(onVideoViewEventHandler);

        //设置DataSource
        mVideoView.setDataSource(new DataSource(mAdDataBean.getAdInfo().get(0).getAdMaterialInfo().getMaterialFeature().get(0).getMaterialUrl()));
        mVideoView.start();

        tvTitle.setText(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdTitle());
        Glide.with(this).load(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppIconUrl()).into(ivIcon);
//        ImageLoader.loadImage(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppIconUrl(), ivIcon);
        btnAction.setText(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdActionDescription());

        packageName = mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppPackageName();
        if(ShuaApplication.adMap == null){
            ShuaApplication.adMap = new HashMap<>();
        }
        if(!TextUtils.isEmpty(packageName)){
            ShuaApplication.adMap.put(packageName, mAdDataBean);
        }

        View.OnClickListener onClickListener = v -> {
            action();

            if (!hasReportClick) {
                hasReportClick = true;
                int[] location = new int[2];
                v.getLocationOnScreen(location);
                int x = location[0];
                int y = location[1];
                startReport(ReportLocationType.Click, String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(x), String.valueOf(y), String.valueOf(x), String.valueOf(y));
            }
            MangoReward.getMGMobRewardListener().onClick();
        };

        btnAction.setOnClickListener(onClickListener);
        btnActionFinish.setOnClickListener(onClickListener);

    }

    private void action() {
        String deepLink = mAdDataBean.getAdInfo().get(0).getAdConversionInfo().getDeeplinkUrl();
        if (!TextUtils.isEmpty(deepLink)) {
            if (MangoUtils.actionDeepLink(this, deepLink)) {
                startReport(ReportLocationType.deeplinkClick);
                return;
            }
        }
        int operationType = mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdOperationType();
        String h5Url = mAdDataBean.getAdInfo().get(0).getAdConversionInfo().getH5Url();
        if (operationType == OperationType.H5.getType()) {
            String title = mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdTitle();
            BrowserActivity.action(MGRewardActivity.this, title, h5Url, mAdDataBean);
        } else if (operationType == OperationType.APP_Download.getType()) {
            String appPackageName = mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppPackageName();
            if(!TextUtils.isEmpty(appPackageName)){
                Intent launchAppIntent = IntentUtils.getLaunchAppIntent(appPackageName);
                if (launchAppIntent != null) {
                    Utils.getApp().startActivity(launchAppIntent);
                    return;
                }
            }
            startDownload(mAdDataBean.getAdInfo().get(0).getAdConversionInfo().getAppDownloadUrl());
        } else if (operationType == OperationType.GTD_Download.getType()) {
            //广点通下载类需要宏替换
            String appDownloadUrl = mAdDataBean.getAdInfo().get(0).getAdConversionInfo().getAppDownloadUrl();
            gtdDownload(appDownloadUrl);
        }
    }

    private void gtdDownload(String url){
        RetrofitUtil.getInstance().getApiService(MyApiService.class)
                .getAdOperation(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserveListener<AdOperationBean>() {
                    @Override
                    public void onNext(AdOperationBean responseBean) {
                       if(responseBean != null && responseBean.getData() != null){
                           String clickid = responseBean.getData().getClickid();
                           ShuaApplication.gdtClickIdMap.put(url, clickid);
                           startDownload(responseBean.getData().getDstlink());
                       }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }

    private void startDownload(String url) {

        Toast.makeText(MGRewardActivity.this, "开始下载", Toast.LENGTH_LONG).show();
        if (!hasReportStartDown) {
            hasReportStartDown = true;
            startReport(ReportLocationType.startDown);
        }
        FileDownloader.setup(this);
        final String savePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator;
        FileDownloader.getImpl().create(url).setPath(savePath, true).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
//                MLog.logd("下载完成：" + task.getTargetFilePath());
                if (!hasReportEndDown) {
                    hasReportEndDown = true;
                    startReport(ReportLocationType.endDown);
                }
                if (!hasReportStartInstall) {
                    hasReportStartInstall = true;
                    startReport(ReportLocationType.startInstall);
                }
                if(TextUtils.isEmpty(packageName)){
                    packageName = AppInfoUtils.getPackage(ShuaApplication.context, task.getTargetFilePath());
                }
                if(!TextUtils.isEmpty(packageName)){
                    ShuaApplication.adMap.put(packageName, mAdDataBean);
                }
                AppUtils.installApp(task.getTargetFilePath());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {
        WebSettings ws = webview.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
        webview.setInitialScale(100);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
//        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);

//        mWebChromeClient = new MyWebChromeClient(this);
//        webview.setWebChromeClient(mWebChromeClient);
//        webview.setWebViewClient(new SimpleWebClient());
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (!hasReportClick) {
                    hasReportClick = true;
                    View v = btnAction;
                    int[] location = new int[2];
                    v.getLocationOnScreen(location);
                    int x = location[0];
                    int y = location[1];
                    startReport(ReportLocationType.Click, String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(x), String.valueOf(y), String.valueOf(x), String.valueOf(y));
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });

    }

    private class SimpleWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (!hasReportClick) {
                hasReportClick = true;
                View v = btnAction;
                int[] location = new int[2];
                v.getLocationOnScreen(location);
                int x = location[0];
                int y = location[1];
                startReport(ReportLocationType.Click, String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(v.getLeft()), String.valueOf(v.getTop()), String.valueOf(x), String.valueOf(y), String.valueOf(x), String.valueOf(y));
            }
            return super.shouldOverrideUrlLoading(view, request);
        }
    }


    private OnVideoViewEventHandler onVideoViewEventHandler = new OnVideoViewEventHandler() {
        @Override
        public void onAssistHandle(BaseVideoView assist, int eventCode, Bundle bundle) {
            super.onAssistHandle(assist, eventCode, bundle);
            if (eventCode == DataInter.Event.EVENT_CODE_ERROR_SHOW) {
//                MLog.logi("播放失败");
                mVideoView.stop();
            }
        }

        @Override
        public void requestRetry(BaseVideoView videoView, Bundle bundle) {
            super.requestRetry(videoView, bundle);
        }
    };

    @Override
    public void onPlayerEvent(int eventCode, Bundle bundle) {
        int coverType = mAdDataBean.getAdInfo().get(0).getAdMaterialInfo().getMaterialFeature().get(0).getCoverType();
        switch (eventCode) {
            case OnPlayerEventListener.PLAYER_EVENT_ON_PLAY_COMPLETE:
//                MLog.logi("视频播放完成");
                isPlayComplete = true;
                startReport(ReportLocationType.endPlay);
                if (coverType == CoverType.HTML_CODE.getType()) {
                    playContainer.setVisibility(View.GONE);
                    finishContainer.setVisibility(View.VISIBLE);
                } else if (coverType == CoverType.IMAGE.getType()) {
                    playContainer.setVisibility(View.GONE);
                    finishContainer.setVisibility(View.VISIBLE);
                }
                finishTimer();
                cancelTimer();
                MangoReward.getMGMobRewardListener().onVideoComplete();
                break;
            case OnPlayerEventListener.PLAYER_EVENT_ON_VIDEO_RENDER_START:
//                MLog.logi("curTime="+curTime+"   isPause="+isPause);
                if (curTime != 0 && !isPause) {
//                    MLog.logi("继续播放");
//                    resumeTimer();
//                } else {
                    MLog.logi("播放器开始渲染视频流");
//                    startTimer();
                    if (coverType == CoverType.HTML_CODE.getType()) {
//                        mAgentWeb = AgentWeb.with(this)
//                                .setAgentWebParent(webContainer, new FrameLayout.LayoutParams(-1, -1))
//                                .useDefaultIndicator()
//                                .setAgentWebWebSettings(getSettings())
//                                .setWebViewClient(new SimpleWebClient())
//                                .setAgentWebUIController(new AgentWebUIControllerImplBase() {
//                                    @Override
//                                    public void onMainFrameError(WebView view, int errorCode, String description, String failingUrl) {
////                                        MLog.loge("errorCode:" + errorCode + ", description:" + description + ", 出错的URL:" + failingUrl);
//                                    }
//                                })
//                                .createAgentWeb()
//                                .ready()
//                                .go("");
//                        WebView webView = mAgentWeb.getWebCreator().getWebView();
                        webview.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MLog.logd("onClick: " + v.getY() + ", " + v.getX());
                            }
                        });
                        webview.setDownloadListener(new DefaultDownloadImpl(this) {
                            @Override
                            protected ResourceRequest createResourceRequest(String url) {
                                return DownloadImpl.getInstance()
                                        .with(MGRewardActivity.this.getApplicationContext())
                                        .url(url)
                                        .quickProgress()
                                        .addHeader("", "")
                                        .setEnableIndicator(true)
                                        .autoOpenIgnoreMD5()
                                        .setRetry(5)
                                        .setBlockMaxTime(100000L);
                            }

                            @Override
                            protected void taskEnqueue(ResourceRequest resourceRequest) {
                                resourceRequest.enqueue(new DownloadListenerAdapter() {
                                    @Override
                                    public void onStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength, Extra extra) {
                                        if (!hasReportStartDown) {
                                            hasReportStartDown = true;
                                            startReport(ReportLocationType.startDown);
                                        }
                                    }

                                    @MainThread
                                    @Override
                                    public void onProgress(String url, long downloaded, long length, long usedTime) {
                                    }

                                    @Override
                                    public boolean onResult(Throwable throwable, Uri path, String url, Extra extra) {
                                        if (!hasReportEndDown) {
                                            hasReportEndDown = true;
                                            startReport(ReportLocationType.endDown);
                                        }
                                        if (!hasReportStartInstall) {
                                            hasReportStartInstall = true;
                                            startReport(ReportLocationType.startInstall);
                                        }
                                        startReport(ReportLocationType.startInstall);
                                        return super.onResult(throwable, path, url, extra);
                                    }
                                });
                            }
                        });
                        webview.loadDataWithBaseURL(null, mAdDataBean.getAdInfo().get(0).getAdMaterialInfo().getMaterialFeature().get(0).getCoverUrl(), "text/html", "UTF-8", null);
                    } else if (coverType == CoverType.IMAGE.getType()) {
                        tvTitleFinish.setText(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdTitle());
//                        ImageLoader.loadImage(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppIconUrl(), ivIconFinish);
                        Glide.with(this).load(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppIconUrl()).into(ivIconFinish);
                        btnActionFinish.setText(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdActionDescription());
//                        ImageLoader.loadImage(mAdDataBean.getAdInfo().get(0).getAdMaterialInfo().getMaterialFeature().get(0).getCoverUrl(), imgFinish);
                        Glide.with(this).load(mAdDataBean.getAdInfo().get(0).getAdMaterialInfo().getMaterialFeature().get(0).getCoverUrl()).into(imgFinish);
                        imgFinishContainer.setVisibility(View.VISIBLE);
                    }

                    MangoReward.getMGMobRewardListener().onExpose();
                }
                break;
            case OnPlayerEventListener.PLAYER_EVENT_ON_START:
//                MLog.logi("开始播放");
                startTimer();
                break;
            case OnPlayerEventListener.PLAYER_EVENT_ON_PAUSE:
//                MLog.logi("暂停播放");
                pauseTimer();
                break;
            case OnPlayerEventListener.PLAYER_EVENT_ON_RESUME:
//                MLog.logi("恢复播放");
                resumeTimer();
                break;
            case OnPlayerEventListener.PLAYER_EVENT_ON_STOP:
//                MLog.logi("停止播放");
                cancelTimer();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (mAgentWeb != null) {
//            mAgentWeb.getWebLifeCycle().onPause();
//        }

        int state = mVideoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
        if (mVideoView.isPlaying()) {
            mVideoView.pause();
        } else {
            mVideoView.stop();
        }
//        pauseTimer();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (mAgentWeb != null) {
//            mAgentWeb.getWebLifeCycle().onResume();
//        }

        int state = mVideoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
        if (mVideoView.isInPlaybackState()) {
            mVideoView.resume();
        } else {
            mVideoView.rePlay(0);
        }
//        resumeTimer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (mAgentWeb != null) {
//            mAgentWeb.getWebLifeCycle().onDestroy();
//        }

        mVideoView.stopPlayback();

//        unregisterReceiver(receiver);

        cancelTimer();
    }


    public void initCountDownTimer(long millisInFuture) {
        long duration = mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdShowDuration() * 1000;
        if(duration==millisInFuture){
            startReport(ReportLocationType.Show);
            startReport(ReportLocationType.startPlay);
        }

//        MLog.logd("开始倒计时：" + millisInFuture);
        cancelTimer();
        mCountDownTimer = new CountDownTimer(millisInFuture, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
//                MLog.logd("倒计时进度：" + millisUntilFinished);
                curTime = millisUntilFinished;
                tvTime.setVisibility(View.VISIBLE);
                tvTime.setText(String.valueOf(millisUntilFinished / 1000));
                isPause = false;
            }

            public void onFinish() {
//                MLog.logd("倒计时完成");
                finishTimer();
            }
        };
    }

    private void startTimer() {
        initCountDownTimer(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAdShowDuration() * 1000);
        isPause = false;
        if (mCountDownTimer != null) {
            mCountDownTimer.start();
        }
    }

    private void resumeTimer() {
        if (curTime == 0) {
            return;
        }
        //将上次当前剩余时间作为新的时长
        initCountDownTimer(curTime);
        if (mCountDownTimer != null) {
            mCountDownTimer.start();
        }
        isPause = false;
    }

    private void pauseTimer() {
        if (!isPause) {
            isPause = true;
            cancelTimer();
        }
    }

    private void finishTimer() {
        tvTime.setVisibility(View.GONE);
        tvClose.setVisibility(View.VISIBLE);
        tvClose.setOnClickListener(v -> {
            if (!isPlayComplete) {
                startReport(ReportLocationType.stopPlay);
            }
            startReport(ReportLocationType.closeAd);
            MangoReward.getMGMobRewardListener().onClose();
            finish();
        });
    }

    private void cancelTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void onBackPressed() {

    }

//    private void initReceiver() {
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
//        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
//        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
//        intentFilter.addDataScheme("package");
//        registerReceiver(receiver, intentFilter);
//    }
//
//    private BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent == null || intent.getAction() == null || intent.getData() == null) {
//                return;
//            }
//            switch (intent.getAction()) {
//                case Intent.ACTION_PACKAGE_ADDED:
//                case Intent.ACTION_PACKAGE_REPLACED: {
//                    String packageName = intent.getData().getSchemeSpecificPart();
////                    MLog.logd(packageName + " 安装或替换成功");
//                    if (packageName.equals(mAdDataBean.getAdInfo().get(0).getAdBaseInfo().getAppPackageName())) {
//                        startReport(ReportLocationType.endInstall);
//                    }
//                    break;
//                }
//            }
//        }
//    };
}